<template>
  <div id="transResult">
    <Splitpanes horizontal>
      <Pane :size="50">
        <vxe-toolbar perfect>
          <template #buttons>
            <div class="smallToolTitle">合并关系</div>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="iloading" @click="findTransResult"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新增" @click="handleAdd"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" @click="handleSave"></vxe-button>
            <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="handleDelete"></vxe-button>
          </template>
        </vxe-toolbar>
        <div class="tableBox">
          <vxe-table show-overflow keep-source ref="transResultRef" height="auto" align="left" :header-cell-style="{ height: '28px', padding: '0px 2px' }" :column-config="{ resizable: true }" :loading="loading" :data="transResultList" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: false, showIcon: false }">
            <vxe-column type="checkbox" width="30" fixed="left" align="center"></vxe-column>
            <vxe-column title="优先级" field="priority" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #edit="{ row }">
                <vxe-input v-model="row.priority" type="text"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column title="条件" field="condition" :edit-render="{}">
              <template #default="{ row }">
                <span>{{ format1(row.condition) }}</span>
              </template>
              <template #edit="{ row }">
                <vxe-select v-model="row.condition" placeholder="请选择条件" clearable transfer>
                  <vxe-option v-for="condition in conditions" :key="condition.value" :label="condition.label" :value="condition.value"></vxe-option>
                </vxe-select>
              </template>
            </vxe-column>
            <vxe-column title="条件取值1" field="conparam1" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #edit="{ row }">
                <vxe-input v-model="row.conparam1" type="text"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column title="条件取值2" field="conparam2" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #edit="{ row }">
                <vxe-input v-model="row.conparam2" type="text"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column title="处理方式" field="transtype" :edit-render="{}">
              <template #default="{ row }">
                <span>{{ format2(row.transtype) }}</span>
              </template>
              <template #edit="{ row }">
                <vxe-select v-model="row.transtype" placeholder="请选择处理方式" clearable transfer>
                  <vxe-option v-for="item in transtypes" :key="item.value" :label="item.label" :value="item.value"></vxe-option>
                </vxe-select>
              </template>
            </vxe-column>

            <vxe-column title="处理取值1" field="transparam1" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #edit="{ row }">
                <vxe-input v-model="row.transparam1" type="text"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column title="处理取值2" field="transparam2" :edit-render="{ autofocus: '.vxe-input--inner' }">
              <template #edit="{ row }">
                <vxe-input v-model="row.transparam2" type="text"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column title="结果标志" field="resultflag" :edit-render="{}">
              <template #default="{ row }">
                <span>{{ format3(row.resultflag) }}</span>
              </template>
              <template #edit="{ row }">
                <vxe-select v-model="row.resultflag" placeholder="请选择结果标志" clearable transfer>
                  <vxe-option v-for="resultflag in resultflags" :key="resultflag.code" :label="resultflag.name" :value="resultflag.code"></vxe-option>
                </vxe-select>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
      </Pane>
    </Splitpanes>
  </div>
</template>
<script lang="ts" setup>
// 引入组件区 ==========
import { reactive, ref, getCurrentInstance, onMounted, watch, inject } from 'vue';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { IsEmpty } from '@/utils/common';
import { VXETable, VxeFormPropTypes, VxeFormInstance, List } from 'vxe-table';
import { Splitpanes, Pane } from 'splitpanes';
import type { VxeTableInstance, VxeTablePropTypes, VxeTableEvents } from 'vxe-table';

// 全局变量定义区 ==========
// 获取屏幕高度
let conHeight = ref(document.documentElement.clientHeight);
let useSize = localStorage.getItem('uiSize');
let loading = ref(false); //模版加载
// let itemLoading = ref(false); //项目加载

let { proxy }: any = getCurrentInstance();
let transResultList: any = reactive([]); //模版表格数据
// let itemDetailList: any = reactive([]); //项目表格数据

// 当前选中项目
let itemDiceInfo: any = reactive({
  id: '',
  instrId: ''
});
//条件
const conditions = [{
  value: '1',
  label: '结果='
}, {
  value: '2',
  label: '结果>'
}, {
  value: '3',
  label: '结果<'
}, {
  value: '4',
  label: '结果>='
}, {
  value: '5',
  label: '结果<='
}, {
  value: '6',
  label: '结果包含'
}, {
  value: '7',
  label: '结果开头='
}, {
  value: '8',
  label: '结果结尾='
}, {
  value: 'Z',
  label: '代码(编程人员专用)'
}
];
// 处理方式
const transtypes = [{
  value: '1',
  label: '结果直接='
}, {
  value: '2',
  label: '包含字符串替换为'
},
{
  value: 'Z',
  label: '代码(编程人员专用)'
}
];
// 结果标志 resultflag
let resultflags: any = reactive([]); //字典表：指控规则类型

let iloading = ref(false);
const transResultRef = ref<VxeTableInstance<RowVO>>(); //表格ref标记

// 方法定义区 =============

//暴露属性和方法
defineExpose({
  initTransResult
});

// 页面加载时更新列表(左侧)
onMounted(() => {
  getDictDetailList();
});

function format1(value) {
  for (const item of conditions) {
    if (item.value == value) {
      return item.label;
    }
  }
}
function format2(value) {
  for (const item of transtypes) {
    if (item.value == value) {
      return item.label;
    }
  }
}
function format3(value) {
  for (const item of resultflags) {
    if (item.code == value) {
      return item.name;
    }
  }
}

//从词典获取所有的报告组
// 获取界面字段
function getDictDetailList() {
  iloading.value = true;
  resultflags.length = 0;
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
    .get(url, { params: { code: 'resultFlag' } })
    .then((res: any) => {
      resultflags.push(...res.data);
      iloading.value = false;
    })
    .catch((err: any) => {
      iloading.value = false;
      proxy.$alert(err, '提示');
    });
}

// 接收父组件传值
function initTransResult(row) {
  itemDiceInfo.id = row.id;
  itemDiceInfo.itemNo = row.itemNo;
  itemDiceInfo.rptGroup = row.rptGroup;
  if (!IsEmpty(row.rptGroup)) {
    findTransResult();
  }

}

function findTransResult() {
  loading.value = true;
  transResultList.length = 0;
  const url = '/lab/trans/result/getTransResult';
  proxy.$http
    .get(url, { params: { itemNo: itemDiceInfo.itemNo, rptGroup: itemDiceInfo.rptGroup } })
    .then((res: any) => {
      transResultList.length = 0;
      transResultList.push(...res.data);
      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('查询列表失败', VxeNotifyType.error);
    });
}

//新增
function handleAdd() {
  const $table = proxy.$refs.transResultRef as any;
  const newRec = {
    // ref: ''
  } as any;

  transResultList.push(newRec);
  $table.reloadData(transResultList);
  $table.setEditRow(newRec);
  proxy.$nextTick(() => {
    setTimeout(() => {
      $table.scrollToRow(newRec);
    }, 50);
  });
}

//删除
function handleDelete() {
  const arr = transResultRef.value?.getCheckboxRecords(true);
  // const sltTemplates = (proxy.$refs.templateTableRef as any).getCheckboxRecords();
  if (!(arr && arr.length > 0 && arr[0])) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        const data = { labTransResultList: arr };
        const url = '/lab/trans/result/batchDeleteTransResult';
        proxy.$http
          .post(url, data)
          .then((res: any) => {
            VxeMessage(res.status.msg, VxeNotifyType.success);
            findTransResult();
            // bacGermFormRef.value?.clearFormData();
          })
          .catch((err: any) => {
            VxeMessage(err, VxeNotifyType.error);
          });
      })
      .catch((err: any) => {
        VxeMessage(err, VxeNotifyType.error);
      });
  }
}
// 保存
async function handleSave() {
  let $Xtable = proxy.$refs.transResultRef;
  if ($Xtable) {
    // 表格实例表用该方法拿到有id的为修改
    const updateRecords = await $Xtable.getUpdateRecords().filter((p: any) => {
      return p.id && p.id !== '';
    });
    // 拿到数组中没有id的数据为新增
    const InsertRecords = transResultList.filter((e: any) => {
      return !e.id || e.id === '';
    });

    const labTransResultList = [] as any[];
    updateRecords.forEach((e: any) => {
      const maItem = {
        id: e.id,
        itemNo: e.itemNo,
        rptGroup: e.rptGroup,
        priority: e.priority,
        condition: e.condition,
        conparam1: e.conparam1,
        conparam2: e.conparam2,
        transtype: e.transtype,
        transparam1: e.transparam1,
        transparam2: e.transparam2,
        resultflag: e.resultflag,
        orgId: e.orgId
      };
      labTransResultList.push(maItem);
    });
    InsertRecords.forEach((e: any) => {
      const maItem = {
        id: e.id,
        itemNo: itemDiceInfo.itemNo,
        rptGroup: itemDiceInfo.rptGroup,
        priority: e.priority,
        condition: e.condition,
        conparam1: e.conparam1,
        conparam2: e.conparam2,
        transtype: e.transtype,
        transparam1: e.transparam1,
        transparam2: e.transparam2,
        resultflag: e.resultflag,
        orgId: e.orgId
      };
      labTransResultList.push(maItem);
    });

    if (labTransResultList.length > 0) {
      const data = { labTransResultList };
      const url = '/lab/trans/result/saveOrUpdateTransResult';
      proxy.$http
        .post(url, data)
        .then((res: any) => {
          VxeMessage('修改成功', VxeNotifyType.success);
          setTimeout(() => {
            findTransResult();
          }, 500);
        })
        .catch((err: any) => {
          VxeMessage('修改失败', VxeNotifyType.success);
        });
    } else {
      VxeMessage('无添加或修改数据', VxeNotifyType.error);
    }
  } else {
    return;
  }

}
</script>
<style lang="scss" scoped>
#transResult {
  height: 100%;

  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }

  // 最右侧质控靶值设定表格
  .tableBox {
    height: calc(100% - 45px);
  }
}
</style>
